package com.google.code.robot;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class HeroConf {
	private String file;

	private HeroConf(String file) {
		this.file = file;
	}

	private static boolean validateXmlFile(String file) {
		return true;
	}

	public static HeroConf getInstance() {
		return HeroConf.getInstance("50data.xml");
	}

	public static HeroConf getInstance(String file) {
		boolean valide = validateXmlFile(file);
		if (!valide)
			return null;

		HeroConf conf = new HeroConf(file);
		return conf;
	}

	public List<Player> getPlyaers() throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		Document doc = xmlReader.read(new File(this.file));
		Element root = doc.getRootElement();
		@SuppressWarnings("rawtypes")
		Iterator players = root.selectNodes("/root/players/player").iterator();

		List<Player> users = new ArrayList<Player>();
		while (players.hasNext()) {
			Element el = (Element) players.next();
			String username = el.attributeValue("username");
			String password = el.attributeValue("password");
			users.add(new Player(username, password));
		}
		return users;
	}

	public String getOutputEncoding() throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		Document doc = xmlReader.read(new File(this.file));
		Element root = doc.getRootElement();
		@SuppressWarnings("rawtypes")
		Iterator ens = root.selectNodes("/root/encodings/stdout").iterator();
		while (ens.hasNext()) {
			Element el = (Element) ens.next();
			String en = el.attributeValue("encoding");
			if (en != null)
				return en;
		}
		return null;
	}
}
